package com.github.yoojia.flow.util;

import com.parkingwang.lang.Consumer;
import com.parkingwang.lang.Try;

/**
 * @author Yoojia Chen (yoojiachen@gmail.com)
 * @since 1.0
 */
public class Classes {

    @SuppressWarnings("unchecked")
    public static <T> void findIfExists(String className, Consumer<T> consumer) {
        try {
            final Class clazz = Classes.class.getClassLoader().loadClass(className);
            final Object object = clazz.newInstance();
            consumer.call((T)object);
        } catch (Exception e) {
            // ignore
            return;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T newInstance(final String className) {
        return Try.die(() ->
                (T) Classes.class.getClassLoader().loadClass(className).newInstance());
    }

    public static String resolveImplClass(String className) {
        if (className.contains(".")) {
            return className;
        } else {
            return "com.github.yoojia.flow.impl." + className;
        }
    }

}
